package org.fengdi.store.service;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.fengdi.store.entity.Storage;
import org.fengdi.store.mapper.StorageMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class StorageServiceImpl extends ServiceImpl<StorageMapper, Storage> implements StorageService {

    @Autowired
    private StorageMapper storageMapper;


    @Override
    public Storage findStorageByCommodityCode(String commodityCode) {
        return storageMapper.findByCommodityCode(commodityCode);
    }

    @Override
    public void decreaseStorage(String code, Integer count) throws RuntimeException {
        // 获取源商品数量
        Storage old = this.storageMapper.findByCommodityCode(code);
        int finalCount = old.getCount() - count;
        if (finalCount < 0) {
            throw new RuntimeException("数量不能小于0");
        }

        UpdateWrapper<Storage> wrapper = new UpdateWrapper<>();
        wrapper.eq("commodity_code", old.getCommodityCode());

        Storage storage = new Storage();
        storage.setCount(finalCount);
        storage.setCommodityCode(code);
        if(!this.update(storage, wrapper)) {
            throw new RuntimeException("更新库存失败");
        }
    }
}
